import React from 'react';
import { Affix, Button, Col, Icon, message, Popconfirm, Popover, Row } from 'antd';
import { connect } from 'react-redux';
import menuRoute from 'routes/menuRoute';
import Condition from 'components/condition';
import errorMessage from 'share/errorMessage';
import ResizeTable from 'components/resize-table';
import SlideFrame from 'components/slide-frame';
import { deepCopy, messages } from 'share/common';
import reimburseService from '../reimbursement/reimbursement.service';
import { ruleItems } from 'containers/expense-reimbursement-control/expense-standard/reimbursement-submission/data-sources';
import EditReimbursement from 'containers/expense-reimbursement-control/expense-standard/reimbursement-submission/reimbursement-submission-new';
import NewCondition from 'containers/expense-reimbursement-control/expense-standard/reimbursement-submission/reimbursement-submission-condition';

const { If } = Condition;

class ReimbursementSubmissionDetail extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      page: 0,
      pageSize: 10,
      pagination: { total: 0, onChange: this.onChangePager },
      infoData: {},
      standardData: [],
      slidParams: {
        content: () => <div/>,
        params: {},
        title: ''
      },
      slideFrameVisible: false,
      columns: [
        {
          title: messages('common.sequence'/*序号*/),
          dataIndex: 'index',
          width: 48,
          render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page
        },
        {
          dataIndex: 'controlItem',
          title: messages('expense-reimbursement-control.key12')/*管控项*/,
          render: (value) =>  <Popover placement="topLeft" content={value}>{value}</Popover>} ,
        {
          dataIndex: 'valueType',
          title: messages('expense-reimbursement-control.key14')/*取值方式*/,
          render: (value) =>  <Popover placement="topLeft" content={value}>{value}</Popover>
        },
        {
          dataIndex: 'condContent',
          title: messages('expense-reimbursement-control.key138')/*条件内容*/,
          render: (value) =>  <Popover placement="topLeft" content={value}>{value || '-'}</Popover>
        },        {
          dataIndex: 'itemOID',
          title: messages('common.operation'/*操作*/),
          width: '80',
          render: (value) => this. renderOperation(value)
        },
      ],
    };
  }

  componentDidMount() {
    this.getInfo();
    this.getStandard();
  }

  //获取规则详情
  getInfo = () => {
    const { params: { ruleOID } } = this.props;
    let { infoData } = this.state;

    const service = () => {
      reimburseService.getRuleInfo(ruleOID)
        .then(res => {
          infoData = res.data;
        })
        .catch(e => {
          errorMessage(e.response);
        })
        .finally(() => {
          this.setState({ infoData, basicInfoLoading: false });
        });
    };

    this.setState({ basicInfoLoading: true }, service);
  };

  //获取基本标准
  getStandard = () => {
    let { page, pageSize, standardData, pagination } = this.state;
    const { params: { ruleOID } } = this.props;
    const params = { page, size: pageSize };
    const service = () => {
      reimburseService.searchControlList(ruleOID, params)
        .then(res => {
          standardData = res.data;
          pagination.current = page + 1;
          pagination.total = Number(res.headers['x-total-count'] || 0);
        })
        .catch(e => {
          errorMessage(e.response);
        })
        .finally(() => {
          this.setState({ standardData, pagination, tableLoading: false });
        });
    };

    this.setState({ tableLoading: true }, service);
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getStandard();
      });
    }
  };

  handleValues = (id, value) => {
    if (id === 'forms') {
      value
        ? value = value.map(item => item.formName)
          .join('，')
        : value = messages('expense-reimbursement-control.key28');/*通用*/
    }

    if (id === 'companys') {
      value
        ? value = value.map(item => item.name)
          .join('，')
        : value = messages('expense-reimbursement-control.key28');/*通用*/
    }

    if (id === 'controlLevel') {
      value === 'WARN'
        ? value = messages('expense-reimbursement-control.key46')/*警告*/
        : value = messages('expense-reimbursement-control.key47');/*禁止*/
    }
    if (id === 'status') {
      value ? value = messages('expense-reimbursement-control.key139')/*启动*/ : value = messages('common.status.disable')/*禁用*/;
    }

    return value ? <Popover content={value}>{value}</Popover> : '-';

  };

  handleEditSlideFrame = (flag) => {
    let { slidParams, infoData, infoData: { ruleOID }, itemOID } = this.state;
    const { params: { setOfBooksId } } = this.props;
    slidParams.title = messages('common.baseInfo');/*基本信息*/
    if (flag === 'rule') {
      slidParams.content = EditReimbursement;
      slidParams.params = { info: infoData, setOfBooksId };
    }

    if (flag === 'standard') {
      slidParams.content = NewCondition;
      slidParams.params = { setOfBooksId, ruleOID, itemOID };
    }

    this.setState({ slidParams }, () => {this.setState({ slideFrameVisible: true });});
  };

  deleteRule = (e, id) => {
    e.preventDefault();
    e.stopPropagation();
    reimburseService.deleteControl(id)
      .then(() => {
        this.getStandard();
        message.success(messages('common.delete.successful')/*删除成功*/);
      });
  };

  onCancel = () => {
    let listUrl = menuRoute.getRouteItem('expense-standard').url;
    this.context.router.push(listUrl);
  };


  afterSlideFrameClose = (type) => {
    this.setState({
      slideFrameVisible: false,
      slidParams: {
        content: () => <div/>,
        params: {},
        title: ''
      }
    });
    if (type === 'rule') {
      this.getInfo();
      return;
    }
    if (type === 'standard') {
      this.getStandard()
    }
  };

  handleRowClick = (itemOID) => {
    this.setState({ itemOID }, () => this.handleEditSlideFrame('standard'));
  };

  handleNewStandard = () => {
    this.setState({ itemOID: void 0 }, () => this.handleEditSlideFrame('standard'));
  };

  renderOperation = (value) => {
    const { tenantMode } = this.props;
    const { infoData } = this.state;
    return (
      infoData.source === 1001 && !tenantMode
        ? '-'
        : (
          <div className="reimbursement-submission-operate">
            <a onClick={(e) => this.handleRowClick(value)}>{messages('common.edit')/*编辑*/}</a>

            <Popconfirm
              title={messages('setting.key272'/*确认删除吗？*/)}
              placement="topRight"
              okText={messages('common.ok')}
              cancelText={messages('common.cancel')}
              onConfirm={(e) => {this.deleteRule(e, value);}}>
              <a className="reimbursement-submission__a_delete">{messages('common.delete')/*删除*/}</a>
            </Popconfirm>
          </div>
        )
    );
  };

  renderHeader = () => {
    const { infoData } = this.state;
    let colItems = deepCopy(ruleItems);
    colItems.splice(0, 0, { id: 'code', label: messages('expense-reimbursement-control.key18')/*规则编码*/ });
    return infoData.ruleOID
      ? <Row type="flex">
        {
          colItems.map(item =>
            <Col span={8} className="reimbursement-submission-header__col">
              <div className="reimbursement-submission-header_name">
                {item.label}
              </div>
              <div className="reimbursement-submission-header_content">
                {this.handleValues(item.id, infoData[item.id])}
              </div>
            </Col>)
        }
      </Row>
      : null;
  };

  renderContent = () => {
    const { tableLoading, standardData, pagination, columns } = this.state;
    return (
      <ResizeTable
        columns={columns}
        loading={tableLoading}
        dataSource={standardData}
        pagination={pagination}
        size="middle"
        bordered
      />
    );
  };


  render() {
    const { tenantMode } = this.props;
    const { infoData, slideFrameVisible, slidParams } = this.state;
    return (
      <section className="reimbursement-submission reimbursement-submission-bg">
        <h3 className="reimbursement-submission-title"> {messages('common.baseInfo')/*基本信息*/}
          <If value={tenantMode || (!tenantMode && infoData.source === 1002)}>
            <a className="reimbursement-submission-edit"
               onClick={() => this.handleEditSlideFrame('rule')}>
              {messages('common.edit')/*编辑*/}
            </a>
          </If>
        </h3>

        <div className="reimbursement-submission-header">
          {this.renderHeader()}
        </div>

        <div className="reimbursement-submission-content">
          <h3
            className="reimbursement-submission-title">{messages('expense-reimbursement-control.key16')/*基本标准*/}</h3>
          <If value={tenantMode || (!tenantMode && infoData.source === 1002)}>
            <Button
              className="reimbursement-submission__button_add"
              type="primary"
              onClick={this.handleNewStandard}>
              {messages('expense-reimbursement-control.key50')/*新增*/}
            </Button>

            <Popover content={messages('expense-reimbursement-control.key140')/*每个条件是and关系，需要同时满足*/}>
              <Icon type="info-circle" className='default-color-font reimbursement-submission-icon'/>
            </Popover>
          </If>
          {this.renderContent()}
        </div>

        <Affix offsetBottom={0} className='reimbursement-submission-footer'>
          <Button onClick={this.onCancel}>{messages('common.back')/*返回*/}</Button>
        </Affix>

        <SlideFrame
          show={slideFrameVisible}
          content={slidParams.content}
          params={slidParams.params}
          title={slidParams.title}
          onClose={() => this.setState({ slideFrameVisible: false })}
          afterClose={this.afterSlideFrameClose}
        />
      </section>
    );
  }
}

ReimbursementSubmissionDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    language: state.main.language
  };
}

ReimbursementSubmissionDetail.propTypes = {};

export default connect(mapStateToProps)(ReimbursementSubmissionDetail);
